<template>
  <div class="app-container" v-loading="loading">
    <my-tree-selector-query
      title="选择主题"
      :current-node-key="queryParams.parentSubjectCode"
      :default-expanded-keys="queryParams.parentSubjectCode ? [queryParams.parentSubjectCode] : []"
      :options="filterSubjectsTreeOptions"
      nodeKey="subjectCode"
      :treeProps="{ children: 'children',label: 'subjectName'}"
      @click-node="handleSubjectNodeClick"
    >
      <div class="filter-wrap" slot="header">
        <div class="item">
          <div class="title">网点</div>
          <treeselect
            v-model="queryParams.branchCode"
            :options="branchDataOptions"
            :normalizer="branchNormalizer"
            :show-count="true"
            placeholder="选择网点"
            class="custom-input-width"
            @select="getFilterBranchIncludeSubject"
            noOptionsText="暂无选项"
            noResultsText="没有匹配的搜索结果"
            :clearable="false"
          />
        </div>
        <div class="item">
          <div class="title">系统类型</div>
          <el-select v-model="queryParams.systemType" @change="getFilterBranchIncludeSubject">
            <el-option v-for="item in systemTypeOptions" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </div>
      </div>
    </my-tree-selector-query>

    <div class="right-wrap">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
        <el-form-item label="主题编码" prop="subjectCode">
          <el-input
            v-model="queryParams.subjectCode"
            placeholder="请输入主题编码"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="主题名称" prop="subjectName">
          <el-input
            v-model="queryParams.subjectName"
            placeholder="请输入主题名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
        </el-form-item>
        <!-- <el-form-item label="网点编码" prop="branchCode">
           <el-input
             v-model="queryParams.branchCode"
             placeholder="请输入网点编码"
             clearable
             size="small"
             @keyup.enter.native="handleQuery"
           />
         </el-form-item>-->
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['items:subject:add']"
          >新增主题
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['items:subject:remove']"
          >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['items:subject:export']"
          >导出
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-copy-document"
            size="mini"
            @click="showCopyParentBranchSubjectsDialog"
            v-hasPermi="['items:subject:copyParentBranchSubjects']"
          >复制网点主题树
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table
        :data="subjectList"
        @selection-change="handleSelectionChange"
        default-expand-all
        row-key="subjectCode"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="主题名称" align="left" prop="subjectName"/>
        <el-table-column label="主题编码" width="190" align="center" prop="subjectCode"/>
        <el-table-column label="系统类型" width="170" align="center" prop="systemType">
          <template #default="scope">
            {{ scope.row.systemType === 1 ? '门户' : scope.row.systemType === 2 ? '填表' : scope.row.systemType === 3 ? '表单电子范例' : scope.row.systemType === 4 ? '智能查询' : '填表验收系统' }}
          </template>
        </el-table-column>
        <el-table-column label="关联网点名称" align="center" prop="branchName"/>
        <el-table-column label="主题包含事项" align="center" prop="serviceSum"/>
        <!--        <el-table-column label="关联网点编码" align="center" prop="branchCode"/>-->
        <el-table-column label="主题图标" align="center" width="80" prop="subjectLogo">
          <template slot-scope="scope">
            <el-popover
              v-if="scope.row.subjectLogo"
              placement="top-start"
              width="300"
              trigger="hover"
            >
              <p> {{ scope.row.subjectLogo }}</p>
              <el-button
                size="small"
                type="primary"
                icon="el-icon-document-copy"
                @click="copyImageUrl(scope.row.subjectLogo)"
              >
                复制图片URL
              </el-button>

              <template slot="reference">
                <el-image
                  fit="contain"
                  :src="scope.row.subjectLogo"
                  :preview-src-list="[scope.row.subjectLogo]"
                  ref="elImage"
                  style="width: 60px; height:60px;background-color: #eee"
                />
              </template>
            </el-popover>
            <template v-else>无</template>
          </template>
        </el-table-column>
        <el-table-column label="同级内排序号" width="100" align="center" prop="sort"/>
        <!--      <el-table-column label="备注" align="center" prop="remark"/>-->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleLookDetail(scope.row)"
              v-hasPermi="['items:subject:detail']"
            >详细信息
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['items:subject:edit']"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['items:subject:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--      <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
              layout="sizes, prev, pager, next, jumper"
            />-->
    </div>

    <copy-subject-tree
      v-model="copyParentBranchSubjectsDialogVisible"
      @getList="getFilterBranchIncludeSubject"
    />

  </div>
</template>

<script>
import MyTreeSelectorQuery from "@/views/components/myTreeSelectorQuery";
import CopySubjectTree from './components/copySubjectTree';
import {
  addSubject,
  delSubject,
  getSubject,
  listSubject,
  selectTCfgSubjectByBranchCode,
  updateSubject
} from "@/api/items/subject";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {handleTree} from "@/utils/ruoyi";

export default {
  name: "Subject",
  components: {
    Treeselect,
    MyTreeSelectorQuery,
    CopySubjectTree
  },

  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 主题表格数据
      subjectList: [],
      // 查询参数
      queryParams: {
        // pageNum: 1,
        // pageSize: 10,
        subjectCode: null,
        subjectName: null,
        branchCode: null,
        parentSubjectCode: null,
        // 默认选中门户
        systemType: '1'
      },
      systemTypeOptions: [
        {value: '1', label: '门户'},
        {value: '2', label: '填表系统'},
        {value: '3', label: '表单电子范例系统'},
        {value: '4', label: '智能查询系统'},
        {value: '5', label: '填表验收系统'},
        {value: '6', label: '导办系统'}
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        subjectName: [
          {required: true, message: "主题名称不能为空", trigger: "blur"}
        ],
        branchCode: [
          {required: true, message: "网点编码不能为空", trigger: "blur"}
        ],
        parentSubjectCode: [
          {required: true, message: "父主题不能为空", trigger: "blur"}
        ]
      },
      // 左侧筛选的主题树
      filterSubjectsTreeOptions: [],
      // 复制主题树弹窗
      copyParentBranchSubjectsDialogVisible: false
    }
  },

  computed: {
    // 网点树形数据
    branchDataOptions() {
      return this.$store.state.device.branchDataOptions || []
    },
  },

  methods: {
    showCopyParentBranchSubjectsDialog() {
      this.copyParentBranchSubjectsDialogVisible = true;
    },

    // 获取左侧选择网点包含的主题树
    async getFilterBranchIncludeSubject(e) {
      await this.$nextTick()
      this.subjectList = []
      this.loading = true;
      selectTCfgSubjectByBranchCode({
        branchCode: this.queryParams.branchCode,
        systemType: this.queryParams.systemType
      }).then(response => {
        // 当前激活主题是否存在列表
        const isInTree = response.rows.find(item => item.subjectCode === this.queryParams.parentSubjectCode)
        // 如果不存在 取消当前激活
        if (!isInTree) {
          this.queryParams.parentSubjectCode = undefined
        } else { // 存在则获取主题
          this.getList()
        }
        // 构造树形数据
        this.filterSubjectsTreeOptions = handleTree(response.rows, "subjectCode", "parentSubjectCode");
      }).finally(() => {
        this.loading = false;
      });
    },

    // 点击左侧主题树
    handleSubjectNodeClick(item) {
      this.queryParams.parentSubjectCode = item.subjectCode;
      this.handleQuery();
    },
    // 复制图片url
    copyImageUrl(url) {
      this.$copyText(url).then(message => {
        this.$modal.msgSuccess({
          message: '复制成功',
        })
      }).catch(err => {
        this.$modal.msgError({
          message: '复制失败',
        })
      })
    },

    /** 转换主题区域树形图数据结构 */
    subjectNormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.subjectCode,
        label: node.subjectName,
        children: node.children || undefined
      };
    },

    /** 转换网点树形图数据结构 */
    branchNormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.branchCode,
        label: node.branchName,
        children: node.children || undefined
      };
    },
    /** 查询主题列表 */
    getList() {
      if (!this.queryParams.parentSubjectCode) return this.$modal.msgWarning('请先在左侧选择主题！')
      this.loading = true;
      listSubject(this.queryParams).then(response => {
        const treeData = handleTree(response.rows, "subjectCode", 'parentSubjectCode');
        // console.log(treeData, 123)
        this.subjectList = treeData;

        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.queryParams.subjectCode = null
      this.queryParams.subjectName = null
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({
        name: 'SubjectDetail',
        query: {
          id: null,
          // type 0：查看 1：修改 2：新增
          type: '2'
        }
      })
    },
    handleUpdate(row) {
      this.$router.push({
        name: 'SubjectDetail',
        query: {
          id: row.id,
          // type 0：查看 1：修改 2：新增
          type: '1'
        }
      })
    },
    // 查看主题详细信息
    handleLookDetail(row) {
      this.$router.push({
        name: 'SubjectDetail',
        query: {
          id: row.id,
          // type 0：查看 1：修改 2：新增
          type: '0'
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSubject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSubject(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的主题，如果该主题存在子主题也会一并删除？').then(function () {
        return delSubject(ids);
      }).then(async () => {
        this.$modal.msgSuccess("删除成功");
        this.getFilterBranchIncludeSubject();
      }).catch(() => {
        console.log('删除失败')
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('items/subject/export', {
        ...this.queryParams
      }, `主题基本信息_${new Date().getTime()}.xlsx`)
    }
  },

  watch: {
    branchDataOptions: {
      immediate: true,
      handler(newValue) {
        if (newValue.length && newValue[0].branchCode) {
          // 默认选择第一个网点
          this.queryParams.branchCode = newValue[0].branchCode;
          this.getFilterBranchIncludeSubject();
        }
      }
    }
  },
  activated() {
    // 重新获取左侧列表
    this.getFilterBranchIncludeSubject()
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  min-height: inherit;
  width: 100%;

  .filter-wrap {
    display: flex;
    flex-direction: column;
    justify-content: center;
    font-size: 14px;
    border-bottom: 1px dashed #dfe4ed;
    margin-bottom: 15px;

    .item {
      display: flex;
      align-items: center;
      margin-bottom: 15px;

      .title {
        white-space: nowrap;
        margin: 0;
        margin-right: 10px;
      }
    }

  }

  .right-wrap {
    flex: 1;
    width: 100%;
    height: 100%;
    overflow: hidden;

    .head-card-wrap {
      display: flex;
      width: 100%;
      min-width: 850px;
      margin-bottom: 20px;
      border: 1px solid #409eff;
      border-radius: 2px;
      background: #fff;
      box-shadow: 0 2px 8px -2px rgb(0, 0, 0, 10%);

      .card-item {
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 75px;
        width: 25%;
        font-size: 16px;

        .name {
          display: flex;
          align-items: center;

          .circle {
            width: 12px;
            height: 12px;
            margin-right: 5px;
            border-radius: 50%;
            background: greenyellow;
          }
        }

        .value {
          margin-top: 8px;
          font-size: 20px;

          span {
            font-size: 18px;
          }
        }

        &:last-child {
          &::after {
            width: 0;
          }
        }

        &::after {
          position: absolute;
          content: '';
          right: 0;
          top: 50%;
          width: 1px;
          height: 60%;
          background: #409eff;
          transform: translateY(-50%);
        }
      }
    }
  }

}

.custom-input-width {
  width: 100%;
}
</style>
